package com.zhanghs.contentcenter.common;

import com.zhanghs.contentcenter.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @Author zhanghongshan
 * @date 2021/10/3 9:42 上午
 */
@RestControllerAdvice
@Slf4j
public class CommonExceptionHandler {

    /**
     * 拦截Exception类的异常
     * @param e 其它异常
     * @return 统一异常返回
     */

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResp<Object> exceptionHandler(Exception e){
        return CommonResp.builder()
                .code(9999).message(e.getMessage()).build();
    }

    /**
     * 拦截 CommonException 的异常
     * @param ex 自定义异常
     * @return 统一异常返回
     */

    @ExceptionHandler(CommonException.class)
    @ResponseBody
    public CommonResp<Object> exceptionHandler(CommonException ex){
        return CommonResp.builder()
                .code(ex.getCode()).message(ex.getMessage()).build();
    }

    /**
     * 处理所有接口数据验证异常
     *
     * @param e 参数异常
     * @return 400异常处理
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResp<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 打印堆栈信息
        log.error(e.getMessage(), e);
        StringBuilder msg = new StringBuilder();
        msg.append("校验失败: ");
        BindingResult bindingResult = e.getBindingResult();
        for (FieldError error : bindingResult.getFieldErrors()) {
            msg.append(error.getDefaultMessage()).append(";");
        }
        return CommonResp.builder().code(400).message(msg.toString()).build();
    }

    /**
     * 404 异常
     * @param e  404 异常
     * @return 404异常
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public CommonResp<Object> notFundException(NoHandlerFoundException e) {
        return CommonResp.builder().code(404).message(e.getMessage()).build();
    }



}
